package com.starmark.gateway.springcloud.provider.filter;

import com.starmark.gateway.springcloud.provider.config.IgnoreUrlConfig;
import com.starmark.gateway.springcloud.provider.service.IRouteService;
import com.starmark.gateway.springcloud.provider.utils.RequestHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.util.Assert;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsProcessor;
import org.springframework.web.cors.reactive.CorsUtils;
import org.springframework.web.cors.reactive.DefaultCorsProcessor;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @author starmark
 * @date 2020/5/11  下午9:29
 */
@Slf4j
public class GatewayCorsWebFilter implements WebFilter {
    @Autowired
    private IRouteService routeService;
    private final CorsProcessor processor;

    private static List<String> configHeaderNames = new ArrayList<>();
    static{
        configHeaderNames.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);
        configHeaderNames.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS);
        configHeaderNames.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);
        configHeaderNames.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);
        configHeaderNames.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS);

    }
    @Autowired
    private IgnoreUrlConfig ignoreUrlConfig;
    public GatewayCorsWebFilter() {
        this.processor = new DefaultCorsProcessor();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getPath().value();
        if (ignoreUrlConfig.isIgnoreUrl(url)) {
            //如果发现是css或者js文件，直接放行
            return chain.filter(exchange);
        }
        String projectCode = RequestHelper.getRequestProjectCode(request);
        Assert.hasText(projectCode, "工程编码不存在");
        CorsConfiguration corsConfiguration = routeService.getGatewayProjectCorsConfiguration(projectCode);
        boolean isValid = this.processor.process(corsConfiguration, exchange);

        if (!isValid || CorsUtils.isPreFlightRequest(request)) {
            return Mono.empty();
        }
        //解决跨域冲突的问题
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(exchange.getResponse()) {

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders=    HttpHeaders.writableHttpHeaders(getDelegate().getHeaders());
                dedupe(httpHeaders);
                return httpHeaders;
            }
            void dedupe(HttpHeaders headers) {
                if (headers == null) {
                    return;
                }
                for (String name : configHeaderNames) {
                    dedupe(headers, name.trim());
                }
            }

            private void dedupe(HttpHeaders headers, String name) {
                List<String> values = headers.get(name);
                if (values == null || values.size() <= 1) {
                    return;
                }

                headers.set(name, values.get(values.size() - 1));

            }
        };

        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }



}
